package com.ysu.shop.handler;

import java.lang.reflect.Method;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.ysu.shop.controller.RoleController;
import com.ysu.shop.exception.UserNoLoginException;
import com.ysu.shop.utils.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

/**
 * @description ：拦截器去获取token并验证token
 */
@Slf4j
public class AuthenticationInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,Object object) throws Exception {
        /** 地址过滤 */
        String uri = request.getRequestURI();
        log.info("url: "+uri);
        if (uri.startsWith("/login") || uri.startsWith("/error")||uri.startsWith("/shop")) {
            return true;
        }
        // 对于跨域请求的验证需要放行
        String method = request.getMethod();
        if ("OPTIONS".equals(method)) {
            return true;
        }
        String token = request.getHeader("Authorization");// 从 http 请求头中取出 token
        if (StrUtil.isBlank(token) || JwtUtil.isExpire(token) ){
            System.out.println("发生错误");
            //重置response
            response.reset();
            //设置编码格式
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json;charset=UTF-8");
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.setHeader("Cache-Control","no-cache");
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("code",401);
            jsonObject.put("msg","请重新登录");
            response.getWriter().print(jsonObject);
            response.getWriter().flush();
            response.getWriter().close();
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse httpServletResponse, Object o,
                           ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse httpServletResponse, Object o,
                                Exception e) throws Exception {
    }
}